import dotenv from 'dotenv';
import path from 'path';

// 加载环境变量
dotenv.config({ path: path.join(process.cwd(), '.env') });

// 环境配置
export const config = {
  // 服务器配置
  NODE_ENV: process.env.NODE_ENV || 'development',
  PORT: parseInt(process.env.PORT || '4000', 10),
  HOST: process.env.HOST || 'localhost',
  BASE_URL: process.env.BASE_URL || 'http://localhost:4000',

  // 数据库配置
  DATABASE_URL: process.env.DATABASE_URL || 'postgresql://username:password@localhost:5432/zhishiku',

  // JWT配置
  JWT_SECRET: process.env.JWT_SECRET || 'your-super-secret-jwt-key-change-in-production',
  JWT_ACCESS_EXPIRES_IN: process.env.JWT_ACCESS_EXPIRES_IN || '24h',
  JWT_REFRESH_EXPIRES_IN: process.env.JWT_REFRESH_EXPIRES_IN || '7d',

  // Redis配置
  REDIS_URL: process.env.REDIS_URL || 'redis://localhost:6379',
  REDIS_PASSWORD: process.env.REDIS_PASSWORD,
  REDIS_DB: parseInt(process.env.REDIS_DB || '0', 10),

  // 邮件配置
  SMTP_HOST: process.env.SMTP_HOST || 'smtp.gmail.com',
  SMTP_PORT: parseInt(process.env.SMTP_PORT || '587', 10),
  SMTP_USER: process.env.SMTP_USER,
  SMTP_PASS: process.env.SMTP_PASS,
  SMTP_FROM: process.env.SMTP_FROM || 'noreply@zhishiku.com',

  // 文件上传配置
  UPLOAD_DIR: process.env.UPLOAD_DIR || 'uploads',
  MAX_FILE_SIZE: parseInt(process.env.MAX_FILE_SIZE || '10485760', 10), // 10MB
  ALLOWED_FILE_TYPES: (process.env.ALLOWED_FILE_TYPES || 'jpg,jpeg,png,gif,pdf,doc,docx,txt,md').split(','),

  // 安全配置
  CORS_ORIGINS: (process.env.CORS_ORIGINS || 'http://localhost:3000,http://localhost:3001').split(','),
  RATE_LIMIT_WINDOW_MS: parseInt(process.env.RATE_LIMIT_WINDOW_MS || '900000', 10), // 15分钟
  RATE_LIMIT_MAX: parseInt(process.env.RATE_LIMIT_MAX || '100', 10),
  SESSION_SECRET: process.env.SESSION_SECRET || 'your-super-secret-session-key',

  // 日志配置
  LOG_LEVEL: process.env.LOG_LEVEL || 'info',
  LOG_FILE: process.env.LOG_FILE || 'logs/app.log',

  // 缓存配置
  CACHE_TTL: parseInt(process.env.CACHE_TTL || '3600', 10), // 1小时
  CACHE_MAX_SIZE: parseInt(process.env.CACHE_MAX_SIZE || '100', 10),

  // 搜索配置
  SEARCH_MAX_RESULTS: parseInt(process.env.SEARCH_MAX_RESULTS || '1000', 10),
  SEARCH_HIGHLIGHT_LENGTH: parseInt(process.env.SEARCH_HIGHLIGHT_LENGTH || '200', 10),

  // 分页配置
  DEFAULT_PAGE_SIZE: parseInt(process.env.DEFAULT_PAGE_SIZE || '20', 10),
  MAX_PAGE_SIZE: parseInt(process.env.MAX_PAGE_SIZE || '100', 10),

  // 用户配置
  DEFAULT_USER_ROLE: process.env.DEFAULT_USER_ROLE || 'VIEWER',
  PASSWORD_MIN_LENGTH: parseInt(process.env.PASSWORD_MIN_LENGTH || '6', 10),
  PASSWORD_MAX_LENGTH: parseInt(process.env.PASSWORD_MAX_LENGTH || '128', 10),

  // 知识库配置
  KNOWLEDGE_BASE_MAX_TITLE_LENGTH: parseInt(process.env.KNOWLEDGE_BASE_MAX_TITLE_LENGTH || '200', 10),
  KNOWLEDGE_BASE_MAX_CONTENT_LENGTH: parseInt(process.env.KNOWLEDGE_BASE_MAX_CONTENT_LENGTH || '100000', 10),

  // 分类配置
  CATEGORY_MAX_NAME_LENGTH: parseInt(process.env.CATEGORY_MAX_NAME_LENGTH || '100', 10),
  CATEGORY_MAX_DEPTH: parseInt(process.env.CATEGORY_MAX_DEPTH || '5', 10),

  // 标签配置
  TAG_MAX_NAME_LENGTH: parseInt(process.env.TAG_MAX_NAME_LENGTH || '50', 10),
  MAX_TAGS_PER_KNOWLEDGE_BASE: parseInt(process.env.MAX_TAGS_PER_KNOWLEDGE_BASE || '20', 10),

  // 评论配置
  COMMENT_MAX_LENGTH: parseInt(process.env.COMMENT_MAX_LENGTH || '1000', 10),
  MAX_COMMENT_DEPTH: parseInt(process.env.MAX_COMMENT_DEPTH || '3', 10),

  // 通知配置
  ENABLE_EMAIL_NOTIFICATIONS: process.env.ENABLE_EMAIL_NOTIFICATIONS === 'true',
  ENABLE_PUSH_NOTIFICATIONS: process.env.ENABLE_PUSH_NOTIFICATIONS === 'true',

  // 监控配置
  ENABLE_HEALTH_CHECKS: process.env.ENABLE_HEALTH_CHECKS !== 'false',
  HEALTH_CHECK_INTERVAL: parseInt(process.env.HEALTH_CHECK_INTERVAL || '30000', 10), // 30秒

  // 备份配置
  ENABLE_AUTO_BACKUP: process.env.ENABLE_AUTO_BACKUP === 'true',
  BACKUP_INTERVAL: process.env.BACKUP_INTERVAL || '0 2 * * *', // 每天凌晨2点
  BACKUP_RETENTION_DAYS: parseInt(process.env.BACKUP_RETENTION_DAYS || '30', 10),

  // 第三方服务配置
  GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
  GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
  GITHUB_CLIENT_ID: process.env.GITHUB_CLIENT_ID,
  GITHUB_CLIENT_SECRET: process.env.GITHUB_CLIENT_SECRET,

  // 开发配置
  ENABLE_SWAGGER: process.env.ENABLE_SWAGGER === 'true',
  ENABLE_GRAPHIQL: process.env.ENABLE_GRAPHIQL === 'true',
  DEBUG_MODE: process.env.DEBUG_MODE === 'true'
};

// 数据库配置
export const databaseConfig = {
  url: config.DATABASE_URL,
  options: {
    logging: config.NODE_ENV === 'development' ? console.log : false,
    pool: {
      min: parseInt(process.env.DB_POOL_MIN || '2', 10),
      max: parseInt(process.env.DB_POOL_MAX || '10', 10),
      acquire: parseInt(process.env.DB_POOL_ACQUIRE || '30000', 10),
      idle: parseInt(process.env.DB_POOL_IDLE || '10000', 10)
    }
  }
};

// Redis配置
export const redisConfig = {
  url: config.REDIS_URL,
  password: config.REDIS_PASSWORD,
  db: config.REDIS_DB,
  retryDelayOnFailover: 100,
  maxRetriesPerRequest: 3
};

// 邮件配置
export const emailConfig = {
  host: config.SMTP_HOST,
  port: config.SMTP_PORT,
  secure: config.SMTP_PORT === 465,
  auth: {
    user: config.SMTP_USER,
    pass: config.SMTP_PASS
  },
  from: config.SMTP_FROM
};

// 文件上传配置
export const uploadConfig = {
  directory: config.UPLOAD_DIR,
  maxSize: config.MAX_FILE_SIZE,
  allowedTypes: config.ALLOWED_FILE_TYPES,
  limits: {
    fileSize: config.MAX_FILE_SIZE,
    files: parseInt(process.env.MAX_FILES_PER_REQUEST || '5', 10)
  }
};

// CORS配置
export const corsConfig = {
  origin: config.CORS_ORIGINS,
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
  exposedHeaders: ['Content-Range', 'X-Total-Count']
};

// 限流配置
export const rateLimitConfig = {
  windowMs: config.RATE_LIMIT_WINDOW_MS,
  max: config.RATE_LIMIT_MAX,
  message: {
    success: false,
    error: '请求过于频繁，请稍后再试'
  },
  standardHeaders: true,
  legacyHeaders: false
};

// 安全配置
export const securityConfig = {
  helmet: {
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        styleSrc: ["'self'", "'unsafe-inline'"],
        scriptSrc: ["'self'"],
        imgSrc: ["'self'", "data:", "https:"],
        connectSrc: ["'self'"],
        fontSrc: ["'self'"],
        objectSrc: ["'none'"],
        mediaSrc: ["'self'"],
        frameSrc: ["'none'"]
      }
    },
    hsts: {
      maxAge: 31536000,
      includeSubDomains: true,
      preload: true
    }
  }
};

// 日志配置
export const loggingConfig = {
  level: config.LOG_LEVEL,
  file: config.LOG_FILE,
  maxSize: '20m',
  maxFiles: '14d',
  format: config.NODE_ENV === 'development' ? 'dev' : 'combined'
};

// 缓存配置
export const cacheConfig = {
  ttl: config.CACHE_TTL,
  maxSize: config.CACHE_MAX_SIZE,
  checkPeriod: 600, // 10分钟检查一次过期
  useClones: false
};

// 验证配置
export const validationConfig = {
  password: {
    minLength: config.PASSWORD_MIN_LENGTH,
    maxLength: config.PASSWORD_MAX_LENGTH,
    requireUppercase: true,
    requireLowercase: true,
    requireNumbers: true,
    requireSpecialChars: false
  },
  username: {
    minLength: 3,
    maxLength: 50,
    pattern: /^[a-zA-Z0-9_-]+$/
  },
  email: {
    pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  }
};

// 导出所有配置
export default config;
